package com.bjc.base.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;

/**
 * 重写HttpServletRequestWrapper
 * request.getInputStream()与request.getReader()只能调用一次，因为是流，读取完就没了。
 * 
 * @author xuzihui
 *
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private byte[] requestBody = null;

	public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		// 缓存请求body
		requestBody = StreamUtils.copyToByteArray(request.getInputStream());

	}

	/**
	 * 重写 getInputStream()
	 */
	@Override
	public ServletInputStream getInputStream() throws IOException {
		if (requestBody == null) {
			requestBody = new byte[0];
		}
		final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
		return new ServletInputStream() {
			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener listener) {

			}
		};
	}

	/**
	 * 重写 getReader()
	 */
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

}
